<template>
  <el-dialog
    :model-value="roleDialogVisible"
    :title="admin ? '分配角色 - ' + admin.adminName : '分配角色'"
    width="40%"
    @close="handleClose"
  >
    <el-form>
      <el-form-item label="角色列表">
        <div v-if="roleList.length > 0" class="role-checkbox-group">
          <el-checkbox-group v-model="selectedRoles">
            <el-checkbox
              v-for="role in roleList"
              :key="role.roleId"
              :value="role.roleId"
              class="role-checkbox"
            >
              {{ role.roleNormalizedName }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <el-empty v-else description="暂无可用角色" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveRoles">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, ref, defineProps, watch } from "vue";
import { getRoles, getAdminRoles, saveAdminRoles } from "@/api/admin";
import { ElMessage } from "element-plus";

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  },
  admin: {
    type: Object,
    required: true,
    default: () => ({}),
  },
});

const emits = defineEmits(["update:modelValue", "initGetList"]);

// 数据初始化
const roleDialogVisible = ref(props.modelValue);
const roleList = ref([]);
const selectedRoles = ref([]);

// 获取角色列表
const getRoleList = async () => {
  try {
    const res = await getRoles();
    roleList.value = Array.isArray(res.data) ? res.data : [];

    if (roleList.value.length === 0) {
      ElMessage.warning("暂无可用角色");
    }
  } catch (error) {
    console.error("获取角色列表失败:", error);
    roleList.value = [];
    ElMessage.error("获取角色列表失败");
  }
};

// 获取用户当前角色
const loadAdminRoles = async () => {
  try {
    if (!props.admin?.adminId) return;

    const res = await getAdminRoles(props.admin.adminId);
    selectedRoles.value = res.data.data;
  } catch (error) {
    selectedRoles.value = [];
  }
};

// 保存角色
const saveRoles = async () => {
  try {
    if (selectedRoles.value.length === 0) {
      ElMessage.warning("请至少选择一个角色");
      return;
    }

    // selectedRoles.value 已经是角色ID数组，直接传递
    await saveAdminRoles(props.admin.adminId, selectedRoles.value);

    ElMessage.success("角色分配成功");
    emits("initGetList");
    handleClose();
  } catch (error) {
    console.error("保存角色失败:", error);
    ElMessage.error(error.message || "保存角色失败");
  }
};

const handleClose = () => {
  emits("update:modelValue", false);
};

// 监听对话框状态
watch(
  () => props.modelValue, //
  (newVal) => {
    roleDialogVisible.value = newVal;
  }
);

// 在对话框打开时获取数据
watch(
  () => roleDialogVisible.value,
  async (newVal) => {
    if (newVal) {
      await getRoleList();
      await loadAdminRoles();
    }
  },
  { immediate: true }
);
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.role-checkbox-group {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  padding: 10px;
}

.role-checkbox {
  margin-right: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep(.el-dialog) {
  min-width: 600px;
}

:deep(.el-form-item__label) {
  font-weight: bold;
  padding-bottom: 10px;
}
</style>
